import { DataSource } from 'typeorm';
import { WorkspaceMember } from '../../../entities/workspace-member.entity';
import { Workspace } from '../../../entities/workspace.entity';
import { User } from '../../../entities/user.entity';
import { WorkspaceMemberRole, UserStatus } from '../../../types/enums';

/**
 * 工作区成员种子数据
 * 负责初始化工作区成员关系
 */
export class WorkspaceMemberSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行工作区成员种子
   */
  async run(): Promise<void> {
    console.log('开始初始化工作区成员数据...');

    const workspaceMemberRepository = this.dataSource.getRepository(WorkspaceMember);
    const workspaceRepository = this.dataSource.getRepository(Workspace);
    const userRepository = this.dataSource.getRepository(User);

    // 查找所有用户
    const adminUser = await userRepository.findOneBy({ username: 'admin' });
    const normalUser = await userRepository.findOneBy({ username: 'user' });
    const guestUser = await userRepository.findOneBy({ username: 'guest' });

    if (!adminUser || !normalUser || !guestUser) {
      console.log('未找到基础用户，跳过工作区成员初始化');
      return;
    }

    // 查找所有工作区
    const workspaces = await workspaceRepository.find();

    if (workspaces.length === 0) {
      console.log('未找到工作区，跳过工作区成员初始化');
      return;
    }

    // 当前时间作为加入时间
    const now = new Date();

    // 为每个工作区添加成员
    for (const workspace of workspaces) {
      // 将管理员加入为所有者
      const adminMember = workspaceMemberRepository.create({
        workspaceId: workspace.id,
        userId: adminUser.id,
        role: WorkspaceMemberRole.OWNER,
        joinedAt: now,
        status: UserStatus.ACTIVE
      });
      await workspaceMemberRepository.save(adminMember);
      console.log(`添加用户 ${adminUser.username} 为工作区 ${workspace.name} 的所有者`);

      // 将普通用户加入为管理员
      const userMember = workspaceMemberRepository.create({
        workspaceId: workspace.id,
        userId: normalUser.id,
        role: WorkspaceMemberRole.ADMIN,
        joinedAt: now,
        status: UserStatus.ACTIVE
      });
      await workspaceMemberRepository.save(userMember);
      console.log(`添加用户 ${normalUser.username} 为工作区 ${workspace.name} 的管理员`);

      // 将访客用户加入为成员
      const guestMember = workspaceMemberRepository.create({
        workspaceId: workspace.id,
        userId: guestUser.id,
        role: WorkspaceMemberRole.MEMBER,
        joinedAt: now,
        status: UserStatus.ACTIVE
      });
      await workspaceMemberRepository.save(guestMember);
      console.log(`添加用户 ${guestUser.username} 为工作区 ${workspace.name} 的成员`);
    }

    console.log('工作区成员数据初始化完成');
  }
} 